package dao;

import model.MemberUser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import static dao.MemberUserDao.createUser;

public class UserAdminDao {
    // 定义用户表名
    String user_table = "member_user";
    Database database = new Database();
    ArrayList<MemberUser> arrayList = new ArrayList<>();
    public static final Logger logger = LogManager.getLogger(MemberAdminDao.class);

    /**
     * 使用用户名查找用户
     *
     * @param username 用户名
     * @param limit    分页
     * @return arrayList 查询到的用户列表数组对象
     */
    public ArrayList<MemberUser> getUser(String username, int limit) {
        try {
            if (username == null) {
                getUserList(limit, database, arrayList);
            } else {
                String getUser = "select * from " + user_table + " where username like  '%" + username + "%' limit " + limit;
                logger.info("getUser SQL:" + getUser);
                try (ResultSet resultSet = database.query(getUser)) {
                    getUserArrayList(arrayList, resultSet);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return arrayList;
    }

    /**
     * @param arrayList 什么
     * @param resultSet 是什么
     * @throws SQLException 怎么做
     */
    private void getUserArrayList(ArrayList<MemberUser> arrayList, ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            MemberUser users = new MemberUser(); // 避免数组被覆盖
            users.setId(resultSet.getInt("id"));
            users.setName(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
            users.setEmail(resultSet.getString("email"));
            users.setState(resultSet.getInt("state"));
            arrayList.add(users);
            logger.info("userList " + arrayList);
        }
    }

    private void getUserList(int limit, Database database, ArrayList<MemberUser> arrayList) throws SQLException {
        String getUser = "select * from " + user_table + " limit " + limit;
        logger.info("getUser SQL:" + getUser);
        try (ResultSet resultSet = database.query(getUser)) {
            getUserArrayList(arrayList, resultSet);
        }
    }

    /**
     * 获取所有的用户
     *
     * @param limit 用户列表分页.
     * @return ArrayList 用户列表数组对象
     * @see SQLException
     */
    public ArrayList<MemberUser> getAllUser(int limit) {
        try {
            getUserList(limit, database, arrayList);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return arrayList;
    }

    /**
     * 添加用户功能
     *
     * @param memberUser 用户对象
     * @return boolean 是否成功添加用户
     */
    public boolean addUser(MemberUser memberUser) {
        boolean flag = true;
        // 至少用户名和密码不能为空
        String isUser = "select username from " + user_table + " where username = '" + memberUser.getUsername() + "'";
        logger.info("isUser SQL:" + isUser);
        try (ResultSet resultSet = database.query(isUser)) {
            if (resultSet.next()) {
                flag = false;
                logger.info("flag is " + false);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (memberUser.getUsername() == null || memberUser.getPassword() == null) {
            logger.info("username or password is null");
            return false;
        } else {
            if (flag) {
                try {
                    return createUser(memberUser, user_table, database);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            } else {
                return false;
            }
        }
    }

    /**
     * 删除用户函数
     *
     * @param id 用户id
     * @return boolean 是否成功删除用户
     */
    public boolean delUser(int id) {
        try {
            String delUser = "delete from " + user_table + " where id = " + id;
            logger.info("delUser SQL:" + delUser);
            try (PreparedStatement preparedStatement = database.getPreparedStatement(delUser)) {
                int isSuccess = preparedStatement.executeUpdate();
                logger.info("delUser SQL query:" + isSuccess);
                return isSuccess != 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改用户资料函数
     * TODO:这个功能待测试
     *
     * @param memberUser 用户对象
     * @return boolean 是否修改用户资料成功
     */
    public boolean modUser(MemberUser memberUser) {
        if (memberUser.getUsername() == null || memberUser.getPassword() == null || memberUser.getId() == 0) {
            logger.info("modUser failed!");
            return false;
        } else {
            try {
                String modUser = "update " + user_table + " set email = ?,username = ? ,password = ? ,state = ? where id = ?";
                PreparedStatement preparedStatement = database.getPreparedStatement(modUser);
                preparedStatement.setString(1, memberUser.getEmail());
                preparedStatement.setString(2, memberUser.getUsername());
                preparedStatement.setString(3, memberUser.getPassword());
                preparedStatement.setInt(4, memberUser.getState());
                preparedStatement.setInt(5, memberUser.getId());
                preparedStatement.executeUpdate();
                logger.info("modUser success by " + preparedStatement);
                return true;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public ArrayList<MemberUser> getUserById(int id) {
        if (id == 0) {
            return null;
        } else {
            String getUser = "select * from " + user_table + " where id = " + id;
            try (ResultSet resultSet = database.query(getUser)) {
                getUserArrayList(arrayList, resultSet);
                logger.info("getUserInfoByID date:" + arrayList);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return arrayList;
    }
}
